

package com.hazelcast.client.impl.clientside;

import com.hazelcast.core.LifecycleService;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiPredicate;

import static com.hazelcast.internal.util.Preconditions.checkNotNull;
import static com.hazelcast.internal.util.Preconditions.checkTrue;

public class ClusterDiscoveryService {

    private final int maxTryCount;
    private final LifecycleService lifecycleService;
    private final List<CandidateClusterContext> candidateClusters;
    private final AtomicInteger index = new AtomicInteger();

    public ClusterDiscoveryService(List<CandidateClusterContext> candidateClusters, int maxTryCount, LifecycleService lifecycleService) {
        checkNotNull(candidateClusters, "candidateClusters cannot be null");
        checkTrue(!candidateClusters.isEmpty(), "candidateClusters cannot be empty");
        checkTrue(maxTryCount >= 0, "maxTryCount must be >= 0");

        this.candidateClusters = candidateClusters;
        this.maxTryCount = maxTryCount;
        this.lifecycleService = lifecycleService;
    }

    public boolean tryNextCluster(BiPredicate<CandidateClusterContext, CandidateClusterContext> function) {
        int tryCount = 0;
        while (lifecycleService.isRunning() && tryCount++ < maxTryCount) {
            for (int i = 0; i < candidateClusters.size(); i++) {
                if (function.test(current(), next())) {
                    return true;
                }
            }
        }
        return false;
    }

    public CandidateClusterContext current() {
        return candidateClusters.get(index.get() % candidateClusters.size());
    }

    private CandidateClusterContext next() {
        return candidateClusters.get(index.incrementAndGet() % candidateClusters.size());
    }

    public void shutdown() {
        for (CandidateClusterContext discoveryService : candidateClusters) {
            discoveryService.getCredentialsFactory().destroy();
        }
    }
}
